package com.mingzhi.rabbitextensiondemo.listener;

import com.mingzhi.rabbitextensiondemo.constant.Constants;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

@Component
public class AckListener {


    /**
     * 监听消息
     *
     * @param message 消息
     * @param channel 通道
     */
    @RabbitListener(queues = Constants.ACK_QUEUE)
    public void handMessage(Message message, Channel channel) throws Exception {
        long diliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            System.out.printf("接收到消息：%s, deliveryTag: %d \n", new String(message.getBody(), "UTF-8"), message.getMessageProperties().getDeliveryTag());
            //进行业务逻辑处理
            int num = 3 / 0;
            System.out.println("处理完成");
            //手动 肯定确认消息 必须要加上这个
            //不然即使这个消费成功了，rabbitmq 中的消息状态还是未确认的
            channel.basicAck(diliveryTag, false);
        } catch (Exception e) {
            channel.basicNack(diliveryTag, false, false);
        }
    }
}
